// 最长回文子串

/**
 * 思路一：
 *    分别拆分为长度1到length的字符串片段
 *    看其是否满足回文字符串的特点
 *    满足就放入数组
 *    然后获取长度最大的那一个，进行返回
 * 
 * 思路二：
 *    
 */

// 判断入参是不是回文字符串
function judgeIsPalindrome(str) {
  let flag = false;
  let len = str.length;
  if (len >= 1) {
    if (len % 2) {
      // 奇数位
      if (len === 1) {
        flag = true;
      } else {
        let midIdx = (len - 1) / 2;
        if (str.slice(0, midIdx).split('').reverse().join("") === str.slice(midIdx + 1)) {
          flag = true;
        }
      }
    } else {
      // 偶数位
      let midIdx = [len / 2 - 1, len / 2];
      if (str.slice(0, midIdx[0] + 1).split('').reverse().join("") === str.slice(midIdx[1])) {
        flag = true;
      }
    }
  }
  return flag;
}

function splitStr(str, gap, flag = false) {
  if (gap === 1) {
    return str[0];
  } else {
    let strAry = [];
    while (str.length >= gap && !flag) {
      let fragment = str.slice(0, gap);
      if (judgeIsPalindrome(fragment)) {
        strAry.push(fragment);
        flag = true;
      }
      str = str.slice(1);
    }
    return strAry;
  }
}

let longestPalindrome = function (str) {
  let len = str.length;
  let ary = [];
  let idx = null;
  // 全部拆分为长短不一的字符串片段
  for (let i = 1; i <= len; i++) {
    ary.push(splitStr(str, i));
  }
  ary = ary.flat();
  let maxLen = Math.max(...ary.map(ls => ls.length));
  ary.forEach((item, index) => {
    if (item.length === maxLen) {
      idx = index;
    }
  })
  return ary[idx];
};

longestPalindrome("azwdzwmwcqzgcobeeiphemqbjtxzwkhiqpbrprocbppbxrnsxnwgikiaqutwpftbiinlnpyqstkiqzbggcsdzzjbrkfmhgtnbujzszxsycmvipjtktpebaafycngqasbbhxaeawwmkjcziybxowkaibqnndcjbsoehtamhspnidjylyisiaewmypfyiqtwlmejkpzlieolfdjnxntonnzfgcqlcfpoxcwqctalwrgwhvqvtrpwemxhirpgizjffqgntsmvzldpjfijdncexbwtxnmbnoykxshkqbounzrewkpqjxocvaufnhunsmsazgibxedtopnccriwcfzeomsrrangufkjfzipkmwfbmkarnyyrgdsooosgqlkzvorrrsaveuoxjeajvbdpgxlcrtqomliphnlehgrzgwujogxteyulphhuhwyoyvcxqatfkboahfqhjgujcaapoyqtsdqfwnijlkknuralezqmcryvkankszmzpgqutojoyzsnyfwsyeqqzrlhzbc");